import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
import { createHtmlPlugin } from 'vite-plugin-html';
import svgr from "vite-plugin-svgr";
import path from "path";

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
    let env = loadEnv(mode, process.cwd());
    let isDev = 'development' === mode;

    return ({
        base: env.VITE_BASEDIR || '/',
        plugins: [
            react(),
            svgr(),
            createHtmlPlugin({
                inject: {
                    data: {
                        injectScript: `<script src="${env.VITE_ICONFONT_URL}"></script>${isDev ? `` : ``}`,
                    }
                }
            }),
        ],
        build: {
            sourcemap: isDev ? 'inline' : false,
            rollupOptions: {
                output: {
                    chunkFileNames: (chunkInfo) => {
                        const { facadeModuleId, name } = chunkInfo || {};
                        if(facadeModuleId && -1 !== facadeModuleId.indexOf('/src') && -1 === name.indexOf('index')) {
                            const dir = facadeModuleId.split('/').slice(-2).slice(-2)[0] || '';

                            if(dir) return `assets/js/${dir}-[name]-[hash].js`;
                        }

                        return "assets/js/[name]-[hash].js";
                    },
                },
            },
        },
        css: {
            preprocessorOptions: {
                scss: {
                    silenceDeprecations: ['legacy-js-api']
                }
            }
        },
        server: {
            host: '0.0.0.0',
            port: 5432,
            proxy: {
                '/api': {
                    target: 'http://10.21.20.69:8089/easy-health',
                    changeOrigin: true,
                    rewrite: (path) => path.replace(/^\/api/, ''),
                },
            },
        },
        resolve: {
            alias: {
                "@": path.resolve(__dirname, "src"),
            }
        },
        define: {
            BASEDIR: JSON.stringify(env.VITE_BASEDIR),
            WEB_NAME: JSON.stringify(env.VITE_WEB_NAME),
            WEB_COPYRIGHT: JSON.stringify(env.VITE_WEB_COPYRIGHT),
            API_PREFIX: JSON.stringify(env.VITE_API_PREFIX),
        },
    });
});
